package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.NewsAutoScanConstants;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Autowired
    WmUserMapper wmUserMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();
        //2.封装查询条件

        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {//状态
            query.eq(WmNews::getStatus, dto.getStatus());
        }
        if (StringUtils.isNotBlank(dto.getKeyword())) {//文章标题
            query.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) {//频道
            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null || dto.getEndPubDate() != null) {
            query.between(WmNews::getPublishTime, dto.getBeginPubDate(),
                    dto.getEndPubDate());
        }

        //获取登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        query.eq(WmNews::getUserId, user.getId());
        //3.执行查询
        //发布时间倒序
        query.orderByDesc(WmNews::getCreatedTime);

        IPage<WmNews> pageParam = new Page<>(dto.getPage(), dto.getSize());

        IPage<WmNews> pageResult = page(pageParam, query);


        //4.返回结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                pageResult.getTotal(), pageResult.getRecords());

        //处理图片封面
        result.setHost(webSite);

        return result;
    }


    /**
     * 自媒体文章发布
     *
     * @param dto
     * @param isSubmit 是否为提交 1 为提交 0为草稿
     * @return
     */
    @Override
    @Transactional
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //保存或修改文章
        WmNews wmNews = new WmNews();
        //参数封装
        BeanUtils.copyProperties(dto, wmNews);
        //文章封面类型
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //处理文章封面
        String images = imageListToStr(dto.getImages(), webSite);
        if (StringUtils.isNotBlank(images)) {
            wmNews.setImages(images);
        }

        saveWmNews(wmNews);
        //关联文章和素材的关系(isSubmit=1提交时关联)

        //解析文章中的图片列表
        List<Map> contentList = JSON.parseArray(dto.getContent(), Map.class);
        List<String> materials = parseContentImages(contentList);
        //1.关联文章中的内容与素材的关系
        if (isSubmit.equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS) && materials.size() > 0) {
            saveRelativeInfoForContent(materials, wmNews.getId());
        }
        //2.关联文章中封面和素材的关系

        if (isSubmit.equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS)) {
            saveRelativeInfoForCover(dto, materials, wmNews);
        }
        //发消息给admin端审核
        HashMap<String, Integer> map = new HashMap<>();
        map.put("wmNewsId",wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,
                JSON.toJSONString(map));

        //返回结果

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //处理封面图片的前缀
        /*String images = wmNews.getImages();
        StringBuffer sb = new StringBuffer();

        if (StringUtils.isNotBlank(images)){
            String[] split = images.split(",");
            for (String image : split) {
                image=webSite+image;
                sb.append(image).append(",");
            }
            images = sb.toString().substring(0,sb.toString().lastIndexOf(","));
            wmNews.setImages(images);
        }*/

        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //上架且发布无法删除
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED)
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UPENABLE)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,
                    "文章已发布,不能删除");
        }
        //删除文章
        removeById(id);
        //删除文章和素材的关系
        wmNewsMaterialMapper.delete(Wrappers
                .<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        updateById(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断文章的状态（只有已审核和已发布的文章才能上下架）
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章未发布," +
                    "无权上下架");
        }

        // 同步到APP端文章id,enable
        if (wmNews.getArticleId()!=null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",dto.getEnable());

            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }


        //执行修改
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public WmNews findById(Integer id) {

        return getById(id);
    }

    /**
     * 修改文章
     *
     * @param wmNews
     * @return
     */
    @Override
    public ResponseResult updateWmNews(WmNews wmNews) {
        boolean flag = updateById(wmNews);
        if (!flag){
            ResponseResult.okResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询需要发布的文章id列表
     *
     * @return
     */
    @Override
    public List<Integer> findRelease() {

        List<WmNews> ids = list(Wrappers.<WmNews>lambdaQuery()
                .le(WmNews::getPublishTime, new Date())
                .in(WmNews::getStatus, 4, 8)
                .select(WmNews::getId));
        List<Integer> idList =
                ids.stream().map(x -> x.getId()).collect(Collectors.toList());
        return idList;
    }


    /**
     * 保存文章的封面和素材的关系
     *
     * @param dto       前端的参数
     * @param materials 文章内容的图片列表(无图片前缀)
     * @param wmNews    文章对象
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        //1.获取dto里的图片封面
        List<String> images = dto.getImages();
        //2.判断type是否为自动（如果是自动需要处理）
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            int size = materials.size();
            if (size > 0 && size <= 2) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (size > 2) {
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null) {
                wmNews.setImages(imageListToStr(images, webSite));
            }
            updateById(wmNews);
        }
        //3.执行保存文章封面和素材的关系
        if (images != null && images.size() > 0) {
            saveRelativeInfoForImage(images, wmNews.getId());
        }

    }

    /**
     * 保存文章封面和图片的关系
     *
     * @param images
     * @param wmNewsId
     */
    private void saveRelativeInfoForImage(List<String> images, Integer wmNewsId) {
        images = images.stream().map(x -> x.replace(webSite, "")
                .replace(" ", "")).collect(Collectors.toList());
        saveRelativeInfo(images, wmNewsId, WemediaConstants.WM_IMAGE_REFERENCE);
    }

    /**
     * 保存文章内容和素材关系
     *
     * @param materials 内容中的图片列表
     * @param wmNewsId  文章id
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer wmNewsId) {
        saveRelativeInfo(materials, wmNewsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }


    /**
     * 执行保存文章素材关系
     *
     * @param materials 素材URL列表
     * @param wmNewsId  文章id
     * @param type      引用类型 0:内容的图片 1：封面图片
     */
    private void saveRelativeInfo(List<String> materials, Integer wmNewsId, Short type) {
        //1.根据url查询素材对应的id
        List<WmMaterial> dbMaterials =
                wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, materials)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));

        if (dbMaterials == null || dbMaterials.size() == 0) {
            CustException.cust(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
        }
        //2.判断文章素材是否存在
        /*HashMap map = new HashMap();*/
        /*for (WmMaterial dbMaterial : dbMaterials) {
            map.put(dbMaterial.getUrl(),dbMaterial.getId());
        }*/


        Map<String, Integer> materialMap =
                dbMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl,
                        WmMaterial::getId));

        //存放素材对应的id
        List<Integer> materialIds = new ArrayList<>();
        for (String url : materials) {
            Integer id = materialMap.get(url);
            //说明数据库的数据被删除
            if (id == null) {
                CustException.cust(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
            }

            materialIds.add(id);
        }
        //3.执行保存
        wmNewsMaterialMapper.saveRelations(materialIds, wmNewsId, type);
    }

    /**
     * 抽取文章内容中的图片的url列表
     *
     * @param contentList 内容列表
     * @return
     */
    private List<String> parseContentImages(List<Map> contentList) {

        List<String> materials = new ArrayList<>();
        for (Map<String, String> content : contentList) {
            if (content.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) {
                String imageUrl = content.get("value")
                        .replace(webSite, "")
                        .replace(" ", "");
                materials.add(imageUrl);
            }
        }

        return materials;
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UPENABLE); // 上架

        if (wmNews.getId() == null) {//新增
            save(wmNews);
        } else {//修改
            //先删后加
            wmNewsMaterialMapper.delete(Wrappers
                    .<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }

    }


    /**
     * 图片列表转字符串，并去除图片前缀
     *
     * @param images  图片列表
     * @param webSite 图片前缀
     */

    private String imageListToStr(List<String> images, String webSite) {
        //抽取前端文章封面列表转换成字符串
        if (images.size() > 0) {
            return images.toString().replace("[", "")
                    .replace("]", "")
                    .replace(webSite, "")
                    .replace(" ", "");
        }

        return null;
    }


    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //处理分页参数

        dto.checkParam();
        Integer page = dto.getPage();  //页码，从1开始
        Integer cpage=(page-1)*dto.getSize();  //起始条数，从0开始
        dto.setPage(cpage);
        //查询分页数据
        if (StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        List<WmNewsVo> newsVoList = wmNewsMapper.findListAndPage(dto);


        //查询总记录数
        long count = wmNewsMapper.findListCount(dto);

        //封装结果返回
        ResponseResult result =new PageResponseResult(page,dto.getSize(),count,newsVoList);
        return result;
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null||wmNews.getUserId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());


        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);

        if (wmUser!=null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult result = ResponseResult.okResult(wmNewsVo);
        result.setHost(webSite);
        return result;
    }


    /**
     * 自媒体文章人工审核
     *
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
       if (dto==null||dto.getId()==null){
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
       }
       //先查后改
        WmNews wmNews = getById(dto.getId());
       if (wmNews==null||wmNews.getStatus().intValue()==9
       ||wmNews.getStatus().intValue()==8){
           return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"文章已审核");
       }
       //修改
        wmNews.setStatus(status);
       if (StringUtils.isNotBlank(dto.getMsg())){
           wmNews.setReason(dto.getMsg());
       }
       updateById(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
